package edit;

import header.RaceType;

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
import java.io.*;

// Displays file name and allows for choosing the character to be edited
public class FileHandler {

	MainFrame t3;
	RaceType r3;
	JFrame frame;
	JScrollPane listScroll;
	JList list;

	// Frame is created here and the list is loaded with file names
	public FileHandler() {
		frame = new JFrame();
		JPanel south = new JPanel();
		JLabel name = new JLabel("Select file");
		DefaultListModel listModel = new DefaultListModel();
		list = new JList(listModel);
		listScroll = new JScrollPane(list);
		frame.getContentPane().add(BorderLayout.NORTH, name);
	//	String workDir = System.getProperty("user.dir");
	//	File dir = new File(workDir);
		File dir = new File(".");
		File[] flist = dir.listFiles();
		for(File f : flist) {
			if(f.isFile())
				listModel.addElement(f);
		}
		frame.getContentPane().add(BorderLayout.CENTER, listScroll);
		JButton load = new JButton("Load");
		south.add(load);
		load.addActionListener(new loadActionListener());
		frame.getContentPane().add(BorderLayout.SOUTH, south);
		frame.setSize(250, 250);
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
	}
	
	// Action Listener for load button. Reads the object, creates a RaceType object and passes it to MainFrame
	class loadActionListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			System.out.println(list.getSelectedValue().toString());
			String fileName = list.getSelectedValue().toString();
			String fName = fileName.replace(".\\", "");
			String cFile = fName.replace(".xml", "");
			System.out.println(fName);
			try {
				FileInputStream fin = new FileInputStream(fName);
				ObjectInputStream ois = new ObjectInputStream(fin);
				r3 = (RaceType) ois.readObject();
				ois.close();
			} catch (Exception ev) {
				//ev.printStackTrace();
				System.out.println(ev.getMessage());
			}
			t3 = new MainFrame(r3);
			frame.setVisible(false);
			frame.dispose();
		}
	}
}
